package dnl.jexem.watchdog;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.thoughtworks.xstream.XStream;

public class HistoryLog {

	private static final File FILE = new File("restarts.log");

	private List<HistoryLogEntry> logs;

	public HistoryLog() {
		if (FILE.exists()) {
			loadFromFile();
		} else {
			logs = new ArrayList<HistoryLogEntry>();
		}
	}

	public void addLog(HistoryLogEntry logEntry) {
		logs.add(logEntry);
		persist();
	}

	public List<HistoryLogEntry> getLogs(String processName) {
		List<HistoryLogEntry> result = new ArrayList<HistoryLogEntry>();
		for (HistoryLogEntry historyLogEntry : logs) {
			if (historyLogEntry.getManagedProcessName().equals(processName)) {
				result.add(historyLogEntry);
			}
		}
		return result;
	}

	public int getRestartsCountFromLast15minuts(String processName) {
		List<HistoryLogEntry> restarts = getLogs(processName);
		int count = 0;
		Date tenMinutesAgo = new Date(System.currentTimeMillis()-15*60*1000);
		for (HistoryLogEntry historyLogEntry : restarts) {
			if(historyLogEntry.getRestartTime().after(tenMinutesAgo)){
				count++;
			}
		}
		return count;
	}

	public void persist() {
		XStream xStream = new XStream();
		try {
			xStream.toXML(logs, new FileWriter(FILE));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@SuppressWarnings("unchecked")
	public void loadFromFile() {
		XStream xStream = new XStream();
		try {
			logs = (List<HistoryLogEntry>) xStream.fromXML(new FileReader(FILE));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
